﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Cloudflare_Dynamic_IP
{
    class DataClass
    {
        private static async Task<String> GetPageContentInString(String url)
        {
            try
            {
                HttpClient client = new HttpClient();
                HttpResponseMessage respond = await client.GetAsync(url);
                respond.EnsureSuccessStatusCode();
                return await respond.Content.ReadAsStringAsync();
            }
            catch (Exception e)
            {
                return String.Format("Error : {0}", e.Message);
            }
        }

        private delegate void AddItemCallback(ListView lv, ListViewItem item);
        private static void AddItem(ListView lv, ListViewItem item)
        {
            if (lv.InvokeRequired)
            {
                AddItemCallback d = new AddItemCallback(AddItem);
                lv.Invoke(d, lv, item);
            }
            else
            {
                lv.Items.Add(item);
            }
        }

        public static async Task<String> GetPublicIP()
        {
            String respondBody = await GetPageContentInString("http://checkip.dyndns.org/");
            if (String.Compare(respondBody.Substring(0, 5), "Error") != 0)
            {
                int firstIndex = respondBody.IndexOf("Address: ") + 9;
                int lastIndex = respondBody.LastIndexOf("</body>");
                return respondBody.Substring(firstIndex, lastIndex - firstIndex);
            }
            else
            {
                return respondBody;
            }
        }

        public static async Task<String> GetDomainRecords(String tkn, String email, String z, ListView list)
        {
            List<ListViewItem> recordsList = new List<ListViewItem>();
            String respondBody = await GetPageContentInString(String.Format(@"https://www.cloudflare.com/api_json.html?a=rec_load_all&tkn={0}&email={1}&z={2}", tkn, email, z));
            if (String.Compare(respondBody.Substring(0, 5), "Error") != 0)
            {
                JObject objJsonData = JObject.Parse(respondBody);
                if (String.Compare((String)objJsonData["result"], "success") == 0)
                {
                    list.Items.Clear();
                    for (Int32 i = 0; i < (Int32)objJsonData["response"]["recs"]["count"]; i++)
                    {
                        ListViewItem item = new ListViewItem();
                        item.Text = (String)objJsonData["response"]["recs"]["objs"][i]["rec_id"];
                        item.SubItems.Add((String)objJsonData["response"]["recs"]["objs"][i]["zone_name"]);
                        item.SubItems.Add((String)objJsonData["response"]["recs"]["objs"][i]["name"]);
                        item.SubItems.Add((String)objJsonData["response"]["recs"]["objs"][i]["type"]);
                        item.SubItems.Add((String)objJsonData["response"]["recs"]["objs"][i]["content"]);
                        item.SubItems.Add((String)objJsonData["response"]["recs"]["objs"][i]["service_mode"]);
                        AddItem(list, item);
                    }
                    return "Finished! Got Domain Records!";
                }
                else if (String.Compare((String)objJsonData["result"], "error") == 0)
                {
                    return String.Format("Error! Getting Domain Records. Message : {0}", (String)objJsonData["msg"]);
                }
                else
                {
                    return "Unknown Error!";
                }
            }
            else
            {
                return respondBody;
            }
        }
        public static async Task<String[]> ChangeDomainRecords(String tkn, String email, String z, ListView list, String Ip)
        {
            List<String> logList = new List<String>();
            foreach (ListViewItem item in list.Items)
            {
                String url = String.Format(@"https://www.cloudflare.com/api_json.html?a=rec_edit&tkn={0}&email={1}&z={2}&ttl=1&service_mode={3}&type={4}&name={5}&content={6}&id={7}", tkn, email, z, item.SubItems[5].Text, item.SubItems[3].Text, item.SubItems[2].Text, Ip, item.Text);
                String respondBody = await GetPageContentInString(url);
                if (String.Compare(respondBody.Substring(0, 5), "Error") != 0)
                {
                    JObject objJsonData = JObject.Parse(respondBody);
                    if (String.Compare((String)objJsonData["result"], "success") == 0)
                    {
                        logList.Add(String.Format("Finished! Updated {0} Record!", item.Text));
                    }
                    else if (String.Compare((String)objJsonData["result"], "error") == 0)
                    {
                        logList.Add(String.Format("Error! Updating {0} Record. Message : {1}", item.Text, (String)objJsonData["msg"]));
                    }
                    else
                    {
                        logList.Add("Unknown Error!");
                    }
                }
                else
                {
                    logList.Add(respondBody);
                }
            }
            return logList.ToArray();
        }
    }
}
